export default {
  namespaced: true,
  state: {
    // 1. 购物车数据
    cartItem: uni.getStorageSync('105-cart') || []
  },
  getters: {
    // 1. 购物车中商品的总数量
    total(state) {
      return state.cartItem.reduce((total, item) => {
        return total += item.goods_count
      }, 0)
    },
    // 2. 勾选商品的总数量
    selectTotal(state) {
      let count = 0
      state.cartItem.forEach(item => {
        if (item.goods_state) {
          count += item.goods_count
        }
      })
      return count
    },
    // 3. 计算已勾选商品的总价
    checkedAmount(state) {
      let total = 0
      state.cartItem.forEach(item => {
        if (item.goods_state) { // 已勾选
          total += item.goods_count * item.goods_price
        }
      })
      return total
    }
  },
  mutations: {
    /**
     * 添加商品到购物车
     * @param {*} state 
     * @param {*} goods 
     */
    addToCart(state, goods) {
      // 如果购物车中有该商品, 则加数量
      // 如果购物车中没有该商品, 则添加该商品
      const someGoods = state.cartItem.find(item => item.goods_id === goods.goods_id)
      if (someGoods) {
        someGoods.goods_count += 1
      } else {
        state.cartItem.push(goods)
      }

      // 把购物车的商品持久化到本地
      uni.setStorageSync('105-cart', state.cartItem)
    },
    /**
     * 修改勾选状态
     * @param {*} state 
     * @param {*} goods 
     */
    updateState(state, goods) {
      const someGoods = state.cartItem.find(item => item.goods_id === goods.goods_id)
      if (someGoods) {
        someGoods.goods_state = !someGoods.goods_state
        // 把购物车的商品持久化到本地
        uni.setStorageSync('105-cart', state.cartItem)
      }
    },
    /**
     * 修改商品的购买数量
     * @param {*} state 
     * @param {*} param1 
     */
    updateCount(state, { goods, num }) {
      const someGoods = state.cartItem.find(item => item.goods_id === goods.goods_id)
      if (someGoods) {
        someGoods.goods_count = num
        // 把购物车的商品持久化到本地
        uni.setStorageSync('105-cart', state.cartItem)
      }
    },
    /**
     * 移除商品
     * @param {*} state 
     * @param {*} goods 
     */
    removeGoods(state, goods) {
      state.cartItem = state.cartItem.filter(item => item.goods_id !== goods.goods_id)
      // 把购物车的商品持久化到本地
      uni.setStorageSync('105-cart', state.cartItem)
    },
    /**
     * 全选和取消全选
     */
    changeChecked(state, flag) {
      state.cartItem.forEach(item => item.goods_state = flag)
      // 把购物车的商品持久化到本地
      uni.setStorageSync('105-cart', state.cartItem)
    }
  },
  actions: {}
}